package com.jms.web.mvc.thread;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class MvcThreadLocalContext {

    private static final ThreadLocal<Map<String, Object>> contextHolder = new ThreadLocal<>();

    public static HttpServletRequest getRequest() {
        Map<String, Object> context = contextHolder.get();
        return context != null ? (HttpServletRequest) context.get("request") : null;
    }

    public static HttpServletResponse getResponse() {
        Map<String, Object> context = contextHolder.get();
        return context != null ? (HttpServletResponse) context.get("response") : null;
    }

    public static void setRequest(HttpServletRequest request) {
        getContextMap().put("request", request);
    }

    public static void setResponse(HttpServletResponse response) {
        getContextMap().put("response", response);
    }

    private static Map<String, Object> getContextMap() {
        Map<String, Object> context = contextHolder.get();
        if (context == null) {
            context = new HashMap<>();
            contextHolder.set(context);
        }
        return context;
    }

    public static void remove() {
        contextHolder.remove();
    }
}
